fpath = '1-0.bin'; %'balloons.png'; 

% inputvideo = 'V3V100013_010.crop.avi'; %'video.avi';
inputvideo = 'R:\fourier\MSPark\object_detection_multi_API\NeoEnvironment\Applications\streaming_loopback_v1_00_a\checker_3ppl_circle_256.avi';
VISUALIZE = 0;  %0 : no visualization validate output file, 1: visualize matlab output

 mov = aviread(inputvideo) ; 
 
nr_frame = size(mov(1,1).cdata, 1);
nc_frame = size(mov(1,1).cdata, 2);
nr = 256; %128; %256
nc = 256; %128; %256;
NUM_FRAMES = 81; %200; %201

MULTI_FPGA = 1;
FIRST_FPGA = '1';
SECOND_FPGA = '3';

% breaking frame into chips
cpf_r = floor(nr_frame/nr); % num of chips per frame
cpf_c = floor(nc_frame/nc); % num of chips per frame
cpf = cpf_r * cpf_c;
CHIPS_PER_FRAME = cpf;

rs = 1;
cs = 1;
re = nr;
ce = nc; %256

r_start = zeros(1,cpf);
c_start = zeros(1,cpf);
r_end = zeros(1,cpf);
c_end = zeros(1,cpf);

% start and end for every chip in the frame
for j = 1:cpf_r
    for k = 1:cpf_c
        ind = (j-1)*cpf_c + k;
        c_start(ind) = cs + (k-1)*nc;
        c_end(ind) = ce + (k-1)*nc;
        r_start(ind) = rs + (j-1)*nr;
        r_end(ind) = re + (j-1)*nr;
    end
end

Nc = 3; %1; % num of center channels

% bin_dat_bar = 1;     %0 : dat file (ascii), 1 : binary file

output_nr = 16; %8; %16; % size of output saliency
output_nc = 16; %8; %16;
%% for comparing hardware result
error_threshold = 1e-3;
result_flag = 1;

bin_dat_bar = 1;     %0 : dat file (ascii), 1 : binary file
% res_fname_0 = '1-o_BAK.bin';
% res_fname_1 = '2-o_BAK.bin';
if (bin_dat_bar == 1)
%     outfilepath=  'R:\fourier\MSPark\Saliency API\NeoEnvironment\Applications\streaming_loopback_v1_00_a\test_result_6\'; %'results\saliency_retina_dma\'; 
%     outfilepath = 'R:\fourier\MSPark\err_output_concerns\test_result_6_256x256\';

%     outfilepath = 'R:\fourier\MSPark\HRL object percept detection API\NeoEnvironment\Applications\streaming_loopback_v1_00_a\test_result_6_256_0519bs\';
%     outfilepath = 'R:\fourier\MSPark\HRL object percept detection API\NeoEnvironment\Applications\streaming_loopback_v1_00_a\test_result_6\';
    outfilepath = 'R:\fourier\MSPark\object_detection_multi_API\NeoEnvironment\Applications\streaming_loopback_v1_00_a\test_result_6_checker_3ppl_circle_256_multiBF\';
else
    outfilepath = 'results\saliency_retina\'; %'results\beta_CFIOM_6cs_256\';
end

input_BINfile = 1; % if input is to be read from binary file
infile_path = 'R:\fourier\MSPark\err_output_concerns\test_result_6\';

logfile = 'R:\fourier\MSPark\err_output_concerns\Matlab_Verification\output_multiFPGA_Sal_checker_interleaveBF.log';

if(VISUALIZE == 1)  %if visualization enabled
    scrsz= get(0,'ScreenSize');
%     h = figure('position',[200 scrsz(4)/3 scrsz(3)/2 scrsz(4)/3]);
    h = figure('position',[10 scrsz(4)/3 scrsz(3) scrsz(4)/3]);
       
    p0 = subplot(1,3,1);
    axis equal
    %%set(gca,'nextplot', 'replacechildren');
    p1 = subplot(1,3,2);
    axis equal    
    p2 = subplot(1,3,3);
    axis equal    

%     p0 = subplot(1,2,1);
%     axis equal
%     p2 = subplot(1,2,2);
%     axis equal       

end

logfile_id = fopen(logfile,'w+');   %open the log file
qout = quantizer('ufixed', [24,20]);  %output data rep
qin = quantizer('ufixed',[8,0]); % for r, g, b values

im_curr = zeros(nr,nc,3);
im_prev = zeros(nr,nc,3);

 
  
 out_mov(1:NUM_FRAMES) = struct('cdata', [],'colormap', []);
                        
   for i = 1:NUM_FRAMES  %size(mov,2) %will go to number of frames 
 
%             if(i == 1)
%                 im_prev = zeros(nr,nc,3); %(size(mov(1,i).cdata));
%             else
%                 im_prev = frame;
%             end
%             frame = mov(1,i).cdata;
%             im_curr = frame;

        prev_chip = mov(1,i).cdata;
        curr_chip = mov(1,i+1).cdata;

     for cp = 1:CHIPS_PER_FRAME
  
        j = cp-1;
        r0 = r_start(cp);
        r1 = r_end(cp);
        c0 = c_start(cp);
        c1 = c_end(cp);
        
        im_curr = curr_chip(r0:r1,c0:c1,:);
        im_prev = prev_chip(r0:r1,c0:c1,:);
        
       %% Create dat files for the input chips
%        rgb2dat_n('3C36F-c.dat', im_curr, 2);
%        rgb2dat_n('3C36F-p.dat', im_prev, 2);

  
        [Sal, iSal, cSal, oSal, mSal, fSal] = saliency_hw_sim(im_prev, im_curr, nr, nc, Nc, i+1);      

    if(bin_dat_bar == 1)    %binary file
        if(MULTI_FPGA == 1)
            if(mod(i, 2)==1)
                out_filename=strcat(outfilepath, num2str(j), 'c', num2str(i), 'f', FIRST_FPGA, 'id', '-TargetBuffer','.bin');
            elseif(mod(i, 2)==0)
                out_filename=strcat(outfilepath, num2str(j), 'c', num2str(i), 'f', SECOND_FPGA, 'id', '-TargetBuffer','.bin');
            end
        else
            out_filename=strcat(outfilepath, num2str(j), 'C', num2str(i), 'F', '-TargetBuffer','.bin');
        end
%             out_filename=strcat(outfilepath,num2str(i),'-','o_BAK','.','bin');     %check file name i-o-BAK.bin exixts
        check_file =0;
        while (check_file ~= 2)
            check_file= exist (out_filename, 'file');
        end
        file_id = fopen(out_filename,'r');
        Bdec=dec2hex(fread(file_id,inf,'uint32'));
        array_out= hex2num(qout,Bdec); 
        fclose(file_id);
        result_hw = reshape(array_out, output_nc, output_nr)';
    elseif(bin_dat_bar == 0)  %dat file
        out_filename=strcat(outfilepath,num2str(i),'-','o_BAK','.','dat');     %check file name i-o-BAK.bin exixts
        check_file =0;
        while (check_file ~= 2)
            check_file= exist (out_filename, 'file');
        end
        array_out = dat2array(out_filename, output_nr*output_nc, qout);          
        result_hw = reshape(array_out, output_nc, output_nr)';
    end

    if(VISUALIZE)
        axes(p0)
%         imagesc(imresize(im_curr, [nr,nc]));
        imagesc(im_curr);
%         title (['Input Frame  ']);
        title (['Input Frame  ', num2str(i)]);

        axes(p1)
        imagesc((Sal/5));        %Visualize REF output
        title (['Ref Saliency  ', num2str(i)]);

%         axes(p2)
%         imagesc(imresize(Sal/5,[nr,nc]));   %Visualize HARDWARE output
% %         title (['FPGA Saliency  ']);
%         title (['FPGA Saliency  ', num2str(i)]); 
        
        pause(0.01) %0.25
  %      out_mov(i)= getframe(h);
    end
    
    abs_error = abs((Sal/5) - (result_hw/5));
    max_error = max(max(abs_error));
    avg_error = mean(mean(abs_error));       

    error_flag = abs_error > error_threshold;
    num_error = sum(sum(error_flag));
    error_flag = error_flag * 1111;

    minsal = min(min(Sal/5));
    maxsal_r = max(max(Sal/5));
    err_r = maxsal_r > 0.99;
    err_r = err_r * 1111;
    
    maxsal_h = max(max(result_hw/5));
    err_h = maxsal_h > 0.99;
    err_h = err_h * 1111;


    fprintf(logfile_id,'Chip %d, Frame %d -- Max255_REF = %d, Max255_HW = %d, Max_Ref = %f, Max_hw = %f, num error = %d, max error = %E, avg error = %E\n', j, i, err_r, err_h, maxsal_r, maxsal_h, num_error, max_error, avg_error);
   end
    
   end
   
%close the log file
 fclose(logfile_id);

 %% Make movie 
%  close(h);
 %movie2avi(out_mov, 'saliency_6cs_256_SX475.avi', 'compression', 'None');
 
        
